import {Button, Input, message, Upload, Steps, Tabs} from 'antd'
import React, {
	forwardRef,
	useEffect,
	useImperativeHandle,
	useState,
} from 'react'
import type {UploadFile} from 'antd/es/upload/interface'
import {useModel} from 'umi'
import styles from './index.less'
import {getPublicDownloadUrl, uploadFileUrl} from '@/service/common/upload'
import {
	getUserNameList,
	historicalFlowList,
	historyList,
} from '@/service/common'

const {TextArea} = Input

type propsType = {
	examineType: boolean // 是否显示审批意见及审批附件
	orgId: number | string // 公司id
	processInstanceId: string // 流程id
	required?: boolean // 附件是否必传
	bizType?: number // 业务类型(1.费用立项 2.采购申请 3.采购合同 4.采购计划 5.付款申请 6.供应商准入 7.司机奖励 8.供应商档案 9.停车场费用结算 10.商品方案 11.渠道结算 12.渠道补扣费 13.证照补办申请 14.渠道拉新奖励 15.盘点计划 16.角色申请 17.司机结算 )
	bizNo?: string // 业务id
}

const bizName: any = {
	0: '',
	1: '费用立项',
	2: '采购申请',
	3: '采购合同',
	4: '采购计划',
	5: '付款申请',
	6: '供应商准入',
	7: '司机奖励',
	8: '供应商档案',
	9: '停车场费用结算',
	10: '商品方案',
	11: '渠道结算',
	12: '渠道补扣费',
	13: '证照补办申请',
	14: '渠道拉新奖励',
	15: '盘点计划',
	16: '角色申请',
	17: '司机结算',
}

const examine = (props: propsType, ref: React.Ref<unknown> | undefined) => {
	const {
		examineType,
		orgId,
		processInstanceId,
		required = false,
		bizType = 0,
		bizNo,
	} = props
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	// 审批备注
	const [notes, setNotes] = useState<string>('')
	const [fileList, setFileList] = useState<UploadFile[]>([])
	const [dataSourse, setDataSourse] = useState<any[]>([])
	const [datas, setDatas] = useState<any[]>([])
	const [userList, setUserList] = useState([])
	const [urlList, setUrlList] = useState([])
	const [refuseUrlList, setRefuseUrlList] = useState([])
	const [processNodesData, setProcessNodesData] = useState<any[]>([])
	const [processNodesDataNew, setProcessNodesDataNew] = useState<any[]>([])
	const [current, setCurrent] = useState(0)
	const [historyRejectData, setHistoryRejectData] = useState<any[]>([])
	const [historyRejectDataNew, setHistoryRejectDataNew] = useState<any[]>([])
	const [activeKey, setActiveKey] = useState('审批意见')
	useEffect(() => {
		/** 获取历史审批记录 */
		historyList({
			orgIds: orgId,
			id: processInstanceId,
			current: 1,
			size: 100,
		})
			.then((res: any) => {
				if (res?.success) {
					const newData: any[] = []
					const userIdArr: number[] = []
					let urlArr: string[] = []
					const processNodesNewData: any[] = []
					const nodesData = res?.data?.records
					nodesData.forEach(
						(item: {assignee: string; activityId: any}) => {
							let isExist = true
							processNodesNewData?.forEach(
								(items: {activityId: any}, index) => {
									if (
										items?.activityId === item?.activityId
									) {
										processNodesNewData[index] = item
										isExist = false
									}
								},
							)
							if (isExist) {
								processNodesNewData.push(item)
							}
						},
					)
					setProcessNodesData(processNodesNewData)
					processNodesNewData?.forEach((item, index) => {
						if (item?.nodeType === 1 || item?.nodeType === 3) {
							if (
								item?.message.substr(0, 1) === '{' &&
								item?.message.substr(-1) === '}'
							) {
								const userName = JSON.parse(
									item?.message,
								)?.userName
								if (!userName) {
									setCurrent(index + 1)
								}
							} else {
								setCurrent(index + 1)
							}
						}
					})
					res?.data?.records?.forEach(
						(item: {
							activityName: string
							message: string
							url: string
							assignee: any
							nodeType: number
						}) => {
							userIdArr.push(Number(item?.assignee))
							if (
								item?.nodeType !== 2 &&
								item?.nodeType !== 4 &&
								item?.assignee
							) {
								newData.push(item)
								let urls = []
								if (item?.nodeType === 3) {
									if (
										item?.message.substr(0, 1) === '{' &&
										item?.message.substr(-1) === '}'
									) {
										urls = JSON.parse(
											item?.message,
										)?.url?.split(',')
									}
								} else {
									urls = item?.url?.split(',')
								}
								urlArr = urlArr.concat(urls)
							}
						},
					)
					if (userIdArr?.length) {
						getUserNameList({userIds: userIdArr}).then(
							(result: any) => {
								if (result?.success) {
									setUserList(result?.data)
								}
							},
						)
					}
					const urls = urlArr
						?.map(Number)
						?.filter((item: number) => item !== 0)
					if (urls?.length) {
						getPublicDownloadUrl(urls)
							.then((result: any) => {
								if (result?.success) {
									setUrlList(result?.data)
								}
							})
							.catch((err: any) => {
								message.error(err)
							})
					}
					setDataSourse(newData)
				}
			})
			.catch((err) => {
				setDataSourse([])
				message.error(err)
			})
		historicalFlowList({
			bizType,
			bizNo,
		}).then((res: any) => {
			if (res?.success) {
				let urlArr: string[] = []
				res?.data?.forEach((items: any) => {
					items?.forEach((item: any) => {
						if (
							item?.nodeType !== 2 &&
							item?.nodeType !== 4 &&
							item?.assignee
						) {
							let urls = []
							if (
								item?.message.substr(0, 1) === '{' &&
								item?.message.substr(-1) === '}'
							) {
								urls = JSON.parse(item?.message)?.url?.split(
									',',
								)
							} else {
								urls = item?.url?.split(',')
							}
							urlArr = urlArr.concat(urls)
						}
					})
				})
				const urls = urlArr
					?.map(Number)
					?.filter((item: number) => item !== 0)
				if (urls?.length) {
					getPublicDownloadUrl(urls)
						.then((result: any) => {
							if (result?.success) {
								setRefuseUrlList(result?.data)
							}
						})
						.catch((err: any) => {
							message.error(err)
						})
				}
				setHistoryRejectData(res?.data)
			}
		})
	}, [])
	useEffect(() => {
		if (userList?.length && dataSourse?.length) {
			const newData = [...dataSourse]
			dataSourse.forEach((item, index) => {
				newData[index].urlData = []
				const userData: any = userList?.find(
					(user: {id: number}) => user?.id === Number(item?.assignee),
				)
				urlList?.forEach((url: {id: number}) => {
					const urls =
						item?.nodeType === 3
							? JSON.parse(item?.message)?.url
							: item?.url
					if (urls?.includes(url?.id.toString())) {
						newData[index]?.urlData.push(url)
					}
				})
				if (userData) {
					newData[index].userName = userData?.name || ''
				}
			})
			setDatas(newData)
		}
	}, [dataSourse, userList, urlList])
	useEffect(() => {
		if (historyRejectData?.length) {
			const newData = [...historyRejectData]
			historyRejectData.forEach((items, indexs: number) => {
				items?.forEach((item: any, index: number) => {
					newData[indexs][index].urlData = []
					const userData: any = userList?.find(
						(user: {id: number}) =>
							user?.id === Number(item?.assignee),
					)
					refuseUrlList?.forEach((url: {id: number}) => {
						const urls =
							item?.nodeType === 3
								? JSON.parse(item?.message)?.url
								: item?.url
						if (urls?.includes(url?.id.toString())) {
							newData[indexs][index]?.urlData.push(url)
						}
					})
					if (userData) {
						newData[indexs][index].userName = userData?.name || ''
					}
				})
			})
			setHistoryRejectDataNew(newData)
		}
	}, [historyRejectData, refuseUrlList])
	useEffect(() => {
		if (userList?.length && processNodesData?.length) {
			const newProcessNodesData = [...processNodesData]
			processNodesData.forEach((item, index) => {
				newProcessNodesData[index].urlData = []
				const userData: any = userList?.find(
					(user: {id: number}) => user?.id === Number(item?.assignee),
				)
				if (userData) {
					newProcessNodesData[index].userName = userData?.name || ''
				}
				urlList?.forEach((url: {id: number}) => {
					const urls =
						item?.nodeType === 3
							? JSON.parse(item?.message)?.url
							: item?.url
					if (urls?.includes(url?.id.toString())) {
						newProcessNodesData[index]?.urlData.push(url)
					}
				})
			})
			setProcessNodesDataNew(newProcessNodesData)
		}
	}, [processNodesData, userList])
	useEffect(() => {
		if (dataSourse?.length) {
			setActiveKey('审批意见')
		} else if (dataSourse?.length === 0 && historyRejectData?.length) {
			setActiveKey('历史审批拒绝记录')
		}
	}, [dataSourse, historyRejectData])

	const uploadProps = {
		action: uploadFileUrl,
		name: fileName,
		data: {
			modelName: 'spAccess',
			targetAttr: 0,
		},
		fileList,
		beforeUpload: (file: any) => {
			const defAccept = [
				'.pdf',
				'.docx',
				'.doc',
				'.doc',
				'.xlsx',
				'.xls',
				'.zip',
				'.jpeg',
				'.jpg',
				'.png',
				'.rar',
			]
			const gs = defAccept
			const lastName = file.name.substring(file.name.lastIndexOf('.'))
			if (!gs.includes(lastName)) {
				message.error('文件格式不正确')
			}
			const isLt200M = file.size / 1024 / 1024 < 200
			if (!isLt200M) {
				message.warning('文件必须小于200MB')
			}
			return isLt200M && lastName
		},
		onChange(info: any) {
			const defAccept = [
				'.pdf',
				'.docx',
				'.doc',
				'.doc',
				'.xlsx',
				'.xls',
				'.zip',
				'.jpeg',
				'.jpg',
				'.png',
				'.rar',
			]
			const gs = defAccept
			const lastName = info.file.name.substring(
				info.file.name.lastIndexOf('.'),
			)
			if (gs.includes(lastName)) {
				if (info.file.status) {
					setFileList(info.fileList)
				}
				if (info.file.status === 'done') {
					message.success(info?.file?.response.msg)
				} else if (info.file.status === 'error') {
					message.warning(info?.file?.response.msg)
				}
			}
		},
	}
	const onTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
		setNotes(e.target.value)
	}
	const onSubmit = () => {
		const examineUrl = fileList?.map(
			(item) => item?.response?.data?.id || item?.uid,
		)
		return {
			message: notes,
			url: examineUrl?.toString(),
		}
	}
	useImperativeHandle(ref, () => ({
		getData: onSubmit,
	}))
	const tabItem = []
	if (datas?.length) {
		tabItem.push({
			label: '审批意见',
			key: '审批意见',
			children: (
				<>
					{' '}
					{datas?.length ? (
						<div className={styles.opinion}>
							<div>审批意见</div>
							{datas?.map((item) => {
								const messages =
									item?.message.substr(0, 1) === '{' &&
									item?.message.substr(-1) === '}'
										? JSON.parse(item?.message)?.message
										: item?.message
								const userName =
									item?.message.substr(0, 1) === '{' &&
									item?.message.substr(-1) === '}'
										? JSON.parse(item?.message)?.userName
										: ''
								return (
									<table border="1">
										<tr>
											<td>
												{userName
													? '申请人'
													: item?.taskName}
											</td>
											<td>
												<span className={styles.status}>
													{userName
														? '作废'
														: item?.auditResults}
												</span>
												<span>
													{userName || item?.userName}
												</span>{' '}
												<span>{item?.endTime}</span>
											</td>
										</tr>
										<tr>
											<td>附件</td>
											<td>
												{item?.urlData?.length ? (
													<>
														{item?.urlData?.map(
															(urlItem: {
																filename: string
																url:
																	| string
																	| undefined
															}) => (
																<p>
																	<span>
																		{
																			urlItem?.filename
																		}
																	</span>
																	<a
																		href={
																			urlItem?.url
																		}
																		download={
																			urlItem?.filename
																		}>
																		下载
																	</a>
																</p>
															),
														)}
													</>
												) : (
													<p>暂无附件</p>
												)}
											</td>
										</tr>
										<tr>
											<td>备注</td>
											<td>{messages || '暂无备注'}</td>
										</tr>
									</table>
								)
							})}
						</div>
					) : (
						''
					)}
				</>
			),
		})
	}
	if (historyRejectDataNew?.length) {
		tabItem.push({
			label: '历史审批拒绝记录',
			key: '历史审批拒绝记录',
			children: (
				<>
					{historyRejectDataNew?.map((items) => (
						<div className={styles.opinion}>
							<div>审批意见</div>
							{items?.map((item: any) => {
								if (item?.assignee === '') {
									return ''
								}
								const messages =
									item?.message.substr(0, 1) === '{' &&
									item?.message.substr(-1) === '}'
										? JSON.parse(item?.message)?.message
										: item?.message
								const userName =
									item?.message.substr(0, 1) === '{' &&
									item?.message.substr(-1) === '}'
										? JSON.parse(item?.message)?.userName
										: ''
								return (
									<table border="1">
										<tr>
											<td>
												{userName
													? '申请人'
													: item?.taskName}
											</td>
											<td>
												<span className={styles.status}>
													{userName
														? '作废'
														: item?.auditResults}
												</span>
												<span>
													{userName || item?.assignee}
												</span>{' '}
												<span>{item?.endTime}</span>
											</td>
										</tr>
										<tr>
											<td>附件</td>
											<td>
												{item?.urlData?.length ? (
													<>
														{item?.urlData?.map(
															(urlItem: {
																filename: string
																url:
																	| string
																	| undefined
															}) => (
																<p>
																	<span>
																		{
																			urlItem?.filename
																		}
																	</span>
																	<a
																		href={
																			urlItem?.url
																		}
																		download={
																			urlItem?.filename
																		}>
																		下载
																	</a>
																</p>
															),
														)}
													</>
												) : (
													<p>暂无附件</p>
												)}
											</td>
										</tr>
										<tr>
											<td>备注</td>
											<td>{messages || '暂无备注'}</td>
										</tr>
									</table>
								)
							})}
						</div>
					))}
				</>
			),
		})
	}
	return (
		<div className={styles.examine}>
			<div className={styles.steps}>
				<div style={{margin: '0 10px 0 10px'}}>
					{bizType ? bizName?.[bizType] : ''}审批流程：
				</div>
				<Steps
					current={current}
					size="small"
					items={processNodesDataNew?.map((item) => ({
						title: item?.activityName,
						description: item?.userName,
					}))}
				/>
			</div>
			{examineType ? (
				<div className={styles.notes}>
					<p>
						<div>审批意见：</div>
						<TextArea
							style={{maxWidth: '700px'}}
							value={notes}
							maxLength={50}
							placeholder="请输入（最多50个字）"
							onChange={onTextChange}
							autoSize={{minRows: 3, maxRows: 3}}
						/>
					</p>
					<p>
						<div className={required ? styles.enclosure : ''}>
							添加附件：
						</div>
						<div>
							<Upload {...uploadProps}>
								{fileList?.length < 3 ? (
									<Button type="link">请选择文件</Button>
								) : (
									''
								)}
							</Upload>
							<div className={styles.uploadTips}>
								附件说明：附件最大支持200M，支持格式：PDF、Word、Excel、JPG、PNG、ZIP、RAR
							</div>
						</div>
					</p>
				</div>
			) : (
				''
			)}
			{datas?.length || historyRejectData?.length ? (
				<Tabs
					type="card"
					onChange={(key) => {
						setActiveKey(key)
					}}
					activeKey={activeKey}
					items={tabItem}
				/>
			) : (
				''
			)}
		</div>
	)
}

export default forwardRef(examine)
